package com.example.demo.util;

import okhttp3.*;
import javax.net.ssl.*;
import java.io.IOException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class BrowserSimulator {
    private static final X509TrustManager trustAllCerts = new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] chain, String authType) {}
        public void checkServerTrusted(X509Certificate[] chain, String authType) {}
        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
    };

    // 只添加浏览器头，不强制设置Content-Encoding
    private static class BrowserHeadersInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request().newBuilder()
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Accept-Encoding", "gzip, deflate, br")
                .build();
            return chain.proceed(request);
        }
    }

    private static final OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .addInterceptor(new BrowserHeadersInterceptor())
        .cookieJar(new CookieJar() {
            private final Map<HttpUrl, List<Cookie>> cookieStore = new HashMap<>();

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                cookieStore.put(url, cookies);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                return cookieStore.getOrDefault(url, Collections.emptyList());
            }
        })
        .sslSocketFactory(createUnsafeSSLContext().getSocketFactory(), trustAllCerts)
        .hostnameVerifier((hostname, session) -> true)
        .build();

    private static SSLContext createUnsafeSSLContext() {
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[]{trustAllCerts}, new java.security.SecureRandom());
            return context;
        } catch (Exception e) {
            throw new RuntimeException("SSL context creation failed", e);
        }
    }

    public static Response execute(Request request) throws IOException {
        return client.newCall(request).execute();
    }
}